import java.io.IOException;
import java.util.Objects;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.jsp.JspFactory;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.PageContext;

public class InitializedPageContextServlet extends HttpServlet {
    private static final long serialVersionUID = -4272150997323956771L;
    private PageContext pageContext;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        pageContext = JspFactory.getDefaultFactory().getPageContext(this, req, resp, null, false, 0, true);
        pageContext.setAttribute("hello", "world");
    }

    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.service(req, resp);
        if (Objects.nonNull(pageContext)) {
            JspWriter out = pageContext.getOut();
            resp.setContentType("text/html;charset=UTF-8");
            out.write("<!DOCTYPE html>");
            out.write("<html>");
            out.write("<head>");
            out.write("<title>标题</title>");
            out.write("</head>");
            out.write("<body>");
            out.write((String) pageContext.getAttribute("hello"));
            out.write("</body>");
            out.write("</html>");
        }
    }

}
